﻿using DT.GoogleAnalytics.Metro;
using FantasyWereld.Code;
using FantasyWereld.Common;
using FantasyWereld.Data;
using FantasyWereld.UserControls;
using FantasyWereld.Views;
using System;
using System.Diagnostics;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Search;
using Windows.Data.Json;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.UI;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Grid App template is documented at http://go.microsoft.com/fwlink/?LinkId=234226

namespace FantasyWereld
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
#if DEBUG
        DateTime startTime = DateTime.Now;
#endif
        static DateTime updateTimeRefreshBadge = DateTime.Now;

        /// <summary>
        /// Initializes the singleton Application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (args.PreviousExecutionState != ApplicationExecutionState.Running)
            {
                bool loadState = (args.PreviousExecutionState == ApplicationExecutionState.Terminated);
                ExtendedSplash extendedSplash = new ExtendedSplash(args.SplashScreen, loadState);
                Window.Current.Content = extendedSplash;

                // Google Analytics helper
                AnalyticsHelper.Setup();

                // Ensure the current window is active
                Window.Current.Activate();
            }

            // Do not repeat app initialization when already running, just ensure that
            // the window is active
            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                if (!String.IsNullOrEmpty(args.Arguments))
                    ((Frame)Window.Current.Content).Navigate(typeof(ItemDetailPage), args.Arguments);

                // Google Analytics helper
                AnalyticsHelper.Setup();

                // Ensure the current window is active
                Window.Current.Activate();
                return;
            }

            // Create ShowNews key if it does not exist
            if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("ShowNews"))
                ApplicationData.Current.RoamingSettings.Values["ShowNews"] = true;

            // Create ShowNews key if it does not exist
            if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("ShowPopupNews"))
                ApplicationData.Current.RoamingSettings.Values["ShowPopupNews"] = true;

            // Load application data
            bool errorOccurred = await LoadAppData();

            // Check if the update frequency may be updated
            if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("UpdateFreqNews"))
            {
                // Determine data folder location
                StorageFolder dataFolder = ApplicationData.Current.LocalFolder;
                bool updateFrequencyfileExists = await FWDataSource.CheckFile(Constants.UPDATE_FREQ_FILE, dataFolder);

                if (updateFrequencyfileExists)
                    // Set roaming value to standard value
                    ApplicationData.Current.RoamingSettings.Values["UpdateFreqNews"] = Constants.TASK_TIMEPERIOD;
            }

            // Reset background timer
            try
            {
                var result = await BackgroundExecutionManager.RequestAccessAsync();
                if (result == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity ||
                    result == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity)
                {
                    foreach (var task in BackgroundTaskRegistration.AllTasks)
                    {
                        if (task.Value.Name == Constants.TASK_NAME)
                            task.Value.Unregister(true);
                    }

                    BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
                    builder.Name = Constants.TASK_NAME;
                    builder.TaskEntryPoint = Constants.TASK_ENTRY;

                    if (ApplicationData.Current.RoamingSettings.Values.ContainsKey("UpdateFreqNews"))
                    {
                        var timerValue = Convert.ToUInt16(ApplicationData.Current.RoamingSettings.Values["UpdateFreqNews"]);
                        builder.SetTrigger(new TimeTrigger(timerValue, false));
                    }
                    else
                        builder.SetTrigger(new TimeTrigger(Constants.TASK_TIMEPERIOD, false));

                    var registration = builder.Register();
                }
            }
            catch
            {
            }

            // Register handler for SuggestionsRequested events from the search pane
            //SearchPane.GetForCurrentView().SuggestionsRequested += OnSuggestionsRequested;

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active

            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and associate it with
                // a SuspensionManager key
                rootFrame = CreateApplicationFrame();
                //Associate the frame with a SuspensionManager key                                
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                // If the app was activated from a secondary tile, show the review
                if (!String.IsNullOrEmpty(args.Arguments))
                {
                    rootFrame.Navigate(typeof(ItemDetailPage), args.Arguments);
                    Window.Current.Content = rootFrame;

                    // Google Analytics helper
                    AnalyticsHelper.Setup();

                    // Ensure the current window is active
                    Window.Current.Activate();
                    return;
                }

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

#if DEBUG
            Debug.WriteLine((DateTime.Now - startTime).ToString());
#endif

            if ((rootFrame.Content == null) && (errorOccurred))
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(ErrorPage)))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            else
                if (rootFrame.Content == null)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    if (!rootFrame.Navigate(typeof(MainPage)))
                    {
                        throw new Exception("Failed to create initial page");
                    }
                }

            // Google Analytics helper
            AnalyticsHelper.Setup();

            // Ensure the current window is active
            Window.Current.Activate();
        }

        private static async System.Threading.Tasks.Task<bool> LoadAppData()
        {
            bool errorOccurred = false;

            // Load website data
            try
            {
                // Create localSettings variable
                Windows.Storage.ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

                // Check version number to determine if a refresh
                // is necessary for the datafiles
                Object value = localSettings.Values["versionNumber"];
                if ((value == null) || (Convert.ToInt32(value.ToString()) != Constants.APP_VERSION))
                {
                    // Delete old datafiles
                    await FWDataSource.DeleteFile(Constants.XML_REVIEWS_FILE_NAME);
                    await FWDataSource.DeleteFile(Constants.XML_BOOKS_FILE_NAME);
                    await FWDataSource.DeleteFile(Constants.SUGGESTION_FILE_NAME);
                    await FWDataSource.DeleteFile(Constants.XML_AUTHORS_FILE_NAME);

                    // Store version number
                    localSettings.Values["versionNumber"] = Constants.APP_VERSION;
                }

                await FWDataSource.LoadDataAsync();

                try
                {
                    // Read authors from disk
                    FWDataSource.ReadAuthorsFromDisk(false);
                }
                catch
                {
                    // On error switch to offline mode
                    FWDataSource.ReadAuthorsFromDisk(true);
                }

                try
                {
                    // Read reviews from disk and fetch images
                    FWDataSource.ReadReviewsFromDisk(false);
                }
                catch
                {
                    // On error switch to offline mode
                    FWDataSource.ReadReviewsFromDisk(true);
                }

                // Read news feed
                await FWDataSource.LoadNewsFeedAsync();

                // Read Facebook feed
                //var array = await FWDataSource.loadFacebookFeedAsync();

                // Process the RSS Feeds asynchronously
                FWDataSource.LoadRemoteDataAsync();
            }
            catch
            {
                errorOccurred = true;

                // Delete old datafiles
                FWDataSource.DeleteFile(Constants.XML_REVIEWS_FILE_NAME);
                FWDataSource.DeleteFile(Constants.XML_BOOKS_FILE_NAME);
                FWDataSource.DeleteFile(Constants.SUGGESTION_FILE_NAME);
                FWDataSource.DeleteFile(Constants.XML_AUTHORS_FILE_NAME);
            }

            return errorOccurred;
        }

        private static Frame CreateApplicationFrame()
        {
            var rootFrame = new Frame();

            // Google Analytics helper
            AnalyticsHelper.Setup();

            rootFrame.Navigated += rootFrame_Navigated;
            return rootFrame;
        }

        static async void rootFrame_Navigated(object sender, NavigationEventArgs e)
        {
            if (e.Uri == null)
            {
                if (e.SourcePageType != null)
                {
                    string uri = "/" + e.SourcePageType.FullName;
                    AnalyticsHelper.TrackPageView(uri);

                    // Set roaming value to new value
                    var badgeValue = Convert.ToInt16(ApplicationData.Current.RoamingSettings.Values["BadgeValue"]);
                    if (badgeValue > 0)
                    {
                        if ((DateTime.Now - updateTimeRefreshBadge).Hours >= Constants.UPDATE_BADGE)
                        {
                            // Reset Timer
                            updateTimeRefreshBadge = DateTime.Now;

                            // Update badge Value
                            XmlDocument _FWDataFile = await Utility.ReadXMLDocumentFromFileAsync(Constants.XML_REVIEWS_FILE_NAME);

                            await BadgeUpdater.UpdateBadgeInfoAsync(_FWDataFile);
                        }

                        FWDataSource.SetCounters();
                    }
                }
            }
            else
            {
                AnalyticsHelper.TrackPageView(e.Uri.ToString());
            }
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await SuspensionManager.SaveAsync();
            deferral.Complete();
        }

        private async void showMessagebox(Exception exception)
        {
            // Load resource handler
            var resourceLoader = new ResourceLoader();

            // Create the message dialog and set its content
            var messageDialog = new MessageDialog(resourceLoader.GetString("ErrorNoInternet"));

            // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
            messageDialog.Commands.Add(new UICommand(resourceLoader.GetString("CloseButton"), new UICommandInvokedHandler(this.CommandInvokedHandler)));

            // Set the command that will be invoked by default
            messageDialog.DefaultCommandIndex = 0;

            // Set the command to be invoked when escape is pressed
            messageDialog.CancelCommandIndex = 1;

            // Show the message dialog
            await messageDialog.ShowAsync();
        }

        private void CommandInvokedHandler(IUICommand command)
        {
            App.Current.Exit();
        }

        void OnSuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args)
        {
            string query = args.QueryText.ToLower();

            string[] terms = FWDataSource.AllKeywords;

            foreach (var term in terms)
            {
                if (term.StartsWith(query))
                    args.Request.SearchSuggestionCollection.AppendQuerySuggestion(term);
            }
        }

        protected override void OnWindowCreated(WindowCreatedEventArgs args)
        {
            SettingsPane.GetForCurrentView().CommandsRequested += (s, e) =>
            {
                // Load resource handler
                var resourceLoader = new ResourceLoader();

                SettingsCommand defaultsCommand = new SettingsCommand("info", "Info",
                    (handler) =>
                    {
                        AboutSettingsFlyout sf = new AboutSettingsFlyout();
                        sf.HeaderBackground = new SolidColorBrush(Constants.SETTINGS_BACKGROUND);
                        sf.Show();
                    });
                e.Request.ApplicationCommands.Add(defaultsCommand);

                SettingsCommand prefCommand = new SettingsCommand("instellingen", resourceLoader.GetString("PrefSettingsHeader"),
                    (handler) =>
                    {
                        PreferencesSettingsFlyout sf = new PreferencesSettingsFlyout();
                        sf.HeaderBackground = new SolidColorBrush(Constants.SETTINGS_BACKGROUND);
                        sf.Show();
                    });
                e.Request.ApplicationCommands.Add(prefCommand);

                SettingsCommand privacyCommand = new SettingsCommand("privacy", resourceLoader.GetString("PrefPrivacyHeader"),
                    (handler) =>
                    {
                        PrivacySettingsFlyout sf = new PrivacySettingsFlyout();
                        sf.HeaderBackground = new SolidColorBrush(Constants.SETTINGS_BACKGROUND);
                        sf.Show();
                    });
                e.Request.ApplicationCommands.Add(privacyCommand);
            };

            base.OnWindowCreated(args);
        }

        /// <summary>
        /// Invoked when the application is activated to display search results.
        /// </summary>
        /// <param name="args">Details about the activation request.</param>
        protected async override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
        {
            // TODO: Register the Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().QuerySubmitted
            // event in OnWindowCreated to speed up searches once the application is already running
            if (!FWDataSource.BooksLoaded)
                try
                {
                    // Read books from disk and fetch images
                    FWDataSource.ReadBooksFromDisk(Constants.BOOKFEED_BD_CODE, false);
                }
                catch
                {
                    // On error switch to offline mode
                    FWDataSource.ReadBooksFromDisk(Constants.BOOKFEED_BD_CODE, true);
                }

            // If the Window isn't already using Frame navigation, insert our own Frame
            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;

            // If the app does not contain a top-level frame, it is possible that this 
            // is the initial launch of the app. Typically this method and OnLaunched 
            // in App.xaml.cs can call a common method.
            if (frame == null)
            {
                // Create a Frame to act as the navigation context and associate it with
                // a SuspensionManager key
                frame = new Frame();
                FantasyWereld.Common.SuspensionManager.RegisterFrame(frame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await FantasyWereld.Common.SuspensionManager.RestoreAsync();
                    }
                    catch (FantasyWereld.Common.SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }
            }

            frame.Navigate(typeof(SearchResultsPage), args.QueryText);
            Window.Current.Content = frame;

            // Google Analytics helper
            AnalyticsHelper.Setup();

            // Ensure the current window is active
            Window.Current.Activate();
        }

    }
}
